package ru.voice2blog.uploader;

import com.dropbox.client.DropboxClient;
import com.dropbox.client.DropboxException;
import com.dropbox.client.TrustedAuthenticator;
import org.apache.http.HttpResponse;
import ru.voice2blog.common.V2BServiceAdapter;
import ru.voice2blog.common.exception.InitException;
import ru.voice2blog.common.exception.UploadException;
import ru.voice2blog.common.uploader.DataUploader;
import ru.voice2blog.common.uploader.UploadResult;

import java.io.File;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * User: ilya.ufo
 * Date: 17.04.11
 * Time: 14:17
 */
public class DropboxUploader extends V2BServiceAdapter implements DataUploader {
    private DropboxClient client;

    public UploadResult upload(File file) throws UploadException {
        HttpResponse resp;
        try {
            resp = client.putFile("dropbox", "/Public", file);
            if (resp == null || resp.getStatusLine().getStatusCode() != 200) {
                throw new UploadException("Error on uploading to dropbox.");
            }
            return new UploadResult(true, getLink(file.getName()));
        } catch (DropboxException e) {
            throw new UploadException("Wasn't able to upload file " + file.getName() + " to dropbox", e);
        }
    }

    private String getLink(String name) throws DropboxException {
        Map map = client.accountInfo(false, null);
        return MessageFormat.format("http://dl.dropbox.com/u/{0}/{1}", map.get("uid").toString(), name);
    }

    @Override
    public void init(Properties properties) throws InitException {
        Map<String, String> config = new HashMap<String, String>();
        putProperties(properties, config, "port", "server", "consumer_secret", "consumer_key", "content_server");

        TrustedAuthenticator auth;
        try {
            auth = new TrustedAuthenticator(config);
            auth.retrieveTrustedAccessToken(properties.getProperty("username"), properties.getProperty("password"));

        } catch (Exception e) {
            throw new InitException("Can't create trusted authenticator", e);
        }

        client = new DropboxClient(config, auth);
    }

    private void putProperties(Properties properties, Map<String, String> config, String... keys) {
        for (String key : keys) {
            String property = properties.getProperty(key);
            if (property == null) {
                throw new IllegalArgumentException("Property with key " + key + " is empty");
            }
            config.put(key, property);
        }
    }
}
